# coding=utf-8
import os
import re
import xml.etree.cElementTree as ET

from retrying import retry

from . import ADB
from .. import utils


class Element(object):
    """
    通过元素定位,需要Android 4.0以上
    """

    def __init__(self, android_ip, xml_filepath=None):
        self.android_ip = android_ip
        self.adb = ADB(android_ip)
        self.pattern = re.compile(r"\d+")
        self.ui_xml_path = xml_filepath or self.get_xml_dir()
        self.check_adb_is_connect()

    @staticmethod
    def get_xml_dir(xml_file_name='ui.xml'):
        base_dir = os.environ.get('OutputDir', os.path.dirname(__file__))
        xml_dir = os.path.join(base_dir, 'xml')
        utils.make_dirs_if_not_exist(xml_dir)
        return os.path.join(xml_dir, xml_file_name)

    def check_adb_is_connect(self):
        flag = self.adb.check_adb_is_connect()
        if not flag:
            raise Exception('{} is not adb connect'.format(self.android_ip))

    @retry(wait_fixed=1000, stop_max_attempt_number=5)
    def ___dump_ui_xml(self):
        self.adb.dump_xml('/sdcard/ui.xml')

    @retry(wait_fixed=1000, stop_max_attempt_number=5)
    def ___get_ui_xml(self):
        self.adb.download_file('/sdcard/ui.xml', self.ui_xml_path)

    def __ui_dump(self):
        self.___dump_ui_xml()
        self.___get_ui_xml()

    def return_elements_attrib_not_none(self, attrib):
        element_list = []
        self.__ui_dump()
        tree = ET.ElementTree(file=self.ui_xml_path)
        tree_iter = tree.iter(tag="node")
        for elem in tree_iter:
            if attrib in elem.attrib and elem.attrib[attrib]:
                element_list.append(elem.attrib[attrib])
        return element_list

    def __find_element(self, attrib, attrib_string, return_list):
        self.__ui_dump()
        point_list = []
        tree = ET.ElementTree(file=self.ui_xml_path)
        tree_iter = tree.iter(tag="node")
        for elem in tree_iter:
            if elem.attrib[attrib] == attrib_string:
                bounds = elem.attrib["bounds"]
                coord = self.pattern.findall(bounds)
                x_point = (int(coord[2]) - int(coord[0])) / 2.0 + int(coord[0])
                y_point = (int(coord[3]) - int(coord[1])) / 2.0 + int(coord[1])
                if return_list:
                    return x_point, y_point
                point_list.append((x_point, y_point))
        return point_list

    def find_element_by_attrib(self, attrib, attrib_string, return_list=None):
        attrib_list = ["resource-id", "class", "text"]
        if attrib not in attrib_list:
            raise Exception('not support {} in {}'.format(attrib, attrib_list))
        return self.__find_element(attrib, attrib_string, return_list)
